package dao.impl;

import dao.DepartmentDao;
import pojo.Department;
import pojo.Employee;
import pojo.Manage;
import view.DepartmentView;

import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class DepartmentImpl implements DepartmentDao {
    private List<Department> departmentList = Manage.getDepartmentList();

    public DepartmentImpl(){
        File loadFile = new File("saveData\\departments");
        if(!loadFile.exists()){
            addDepartment(new Department(1000,"财务部"));
            addDepartment(new Department(1100,"销售部"));
            addDepartment(new Department(1200,"生产部"));
            addDepartment(new Department(1300,"人力资源部"));
            addDepartment(new Department(1400,"采购部"));
        }
    }

    @Override
    public void addDepartment(Department department) {
        departmentList.add(department);
        Manage.saveDepartment(departmentList);
    }

    @Override
    public void delDepartment(int id) {
        boolean exist = false;
        Iterator iterator = departmentList.iterator();
        while(iterator.hasNext()){
            Department department = (Department) iterator.next();
            if(department.getId() == id){
                exist = true;
                departmentList.remove(department);
                break;
            }
        }
        if(exist)
            Manage.saveDepartment(departmentList);
        else
            System.out.println("部门id不存在");
    }

    @Override
    public void updateDepartment(int id, int newId, String name) {
        int updateId = 0, empId = 0;
        List<Employee> list = Manage.getEmployeeList();
        Iterator iterator = departmentList.iterator();
        while(iterator.hasNext()){
            Department department = (Department) iterator.next();
            if(department.getId() == id){
                department.update(newId,name);
                departmentList.set(updateId,department);
                for(Employee employee: list){
                    if(employee.getDepartment().getId() == id){
                        employee.updateDepartment(department);
                        list.set(empId,employee);
                        Manage.saveEmployee(list);
                    }
                    empId += 1;
                }
                break;
            }
            updateId += 1;
        }
        Manage.saveDepartment(departmentList);
    }

    @Override
    public Department selectDepartment(int id) {
        Iterator iterator = departmentList.iterator();
        while(iterator.hasNext()){
            Department department = (Department) iterator.next();
            if(department.getId() == id){
                return department;
            }
        }
        return null;
    }

    @Override
    public void showALLDepartment() {
        DepartmentView.printAllDepartment(departmentList);
    }
}
